package baidu

import (
	"fmt"
	"gitee.com/dreamwood/ez-go/tools"
	"net/http"
	"os"
	"strings"
)

type TTSParam struct {
	Text string `json:"tex"`
	Tok  string `json:"tok"`
	Cuid string `json:"cuid"`
	Ctp  string `json:"ctp"`
	Lan  string `json:"lan"`
	Spd  int    `json:"spd"`
	Vol  int    `json:"vol"`
	Per  int    `json:"per"`
	Aue  int    `json:"aue"`
}

func NewTTSParam(text string) *TTSParam {
	return &TTSParam{
		Text: text,
		Tok:  GetAccessToken(),
		Cuid: "123456LJZ!2024",
		Ctp:  "1",
		Lan:  "zh",
		Spd:  1,
		Vol:  5,
		Per:  3,
		Aue:  3,
	}
}

const ttsUrl = `https://tsn.baidu.com/text2audio`

func GetAndSaveTts(text string) string {
	p := NewTTSParam(text)
	reader := strings.NewReader(fmt.Sprintf(
		"tex=%s&tok=%s&cuid=%s&ctp=%s&lan=%s&spd=%d&vol=%d&per=%d&aue=%d",
		p.Text, p.Tok, p.Cuid, p.Ctp, p.Lan, p.Spd, p.Vol, p.Per, p.Aue,
	))
	rest, e := http.Post(ttsUrl, "application/json", reader)
	println(rest.Status)
	defer rest.Body.Close()
	if e != nil {
		println(e.Error())
		return ""
	}
	if rest.StatusCode == 200 {
		println("success")
	}
	//从Body读取音频内容写入mp3文件
	mp3File := fmt.Sprintf("mp3/%s.mp3", tools.CreateRandString(12))
	//mp3File := "testEn.mp3"
	f, e := os.Create(mp3File)
	defer f.Close()
	if e != nil {
		println(e.Error())
		return ""
	}
	_, e = f.ReadFrom(rest.Body)
	if e != nil {
		println(e.Error())
		return ""
	}
	defer f.Close()
	println("保存成功")
	return mp3File
}
